﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;

namespace WebUI.Controls
{
    public partial class PurchasePaymentListCtrl : BaseListControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);
        }

        public bool ReadOnly
        {
            get { return (bool)ViewState[ClientID + "_ReadOnly"]; }
            set { ViewState[ClientID + "_ReadOnly"] = value; }
        }

        public string Title
        {
            get { return lblTitle.Text; }
            set { lblTitle.Text = value; }
        }

        protected override void grid_OnItemCreated(object sender, DataGridItemEventArgs e)
        {
            base.grid_OnItemCreated(sender, e);

            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.SelectedItem)
            {
                TextBox txtBalance = e.Item.FindControl("txtBalance") as TextBox;
                Label lblBalance = e.Item.FindControl("lblBalance") as Label;

                if (lblBalance != null)
                {
                    lblBalance.Visible = ReadOnly;
                    txtBalance.Visible = !ReadOnly;
                }
            }
        }

        public void Pay(int methodID)
        {
            if (SourceObject == null)
                return;
            String oldFilter = SourceObject.Filter;

            SourceObject.Rewind();
            for (int i = 0; i < grid.Items.Count; i++)
            {
                DataGridItem item = grid.Items[i];
                int id = (int)grid.DataKeys[i];

                SourceObject.Filter = "ID = " + id.ToString();
                if (SourceObject.RowCount > 0)
                {
                    TextBox txtBalance = item.FindControl("txtBalance") as TextBox;
                    CheckBox cbSelect = item.FindControl("cbSelect") as CheckBox;

                    if (cbSelect.Checked)
                    {
                        IPayment paymentObj = (IPayment)SourceObject;
                        paymentObj.Pay(decimal.Parse(txtBalance.Text), methodID, SessionUser.ID);
                    }
                }

                SourceObject.MoveNext();
            }

            SourceObject.Save();
            SourceObject.Filter = oldFilter;
        }
    }
}